package com.xiguaji.tiktok.task.blogger.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.tiktok.task.blogger.Blogger;
import com.xiguaji.tiktok.task.blogger.repository.BloggerRepository;
import com.xiguaji.tiktok.task.blogger.spider.BloggerClient;
import com.xiguaji.tiktok.task.blogger.spider.BloggerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class SaveBloggerEventListener implements IEventListener<SaveBloggerEventListener.SaveBloggerEvent> {
    @Autowired
    BloggerRepository bloggerRepository;

    @Autowired
    BloggerClient bloggerClient;

    @Autowired
    Blogger.BloggerMapper bloggerMapper;

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(SaveBloggerEvent event) {
        if (!event.needUpdate) {
            //过滤一轮不需要update的Id,减轻bloggerClient压力
            event.uids = bloggerRepository.getNotExistBloggerIds(event.uids);
        }

        if (CollectionUtils.isEmpty(event.uids)) return;

        event.uids.parallelStream().forEach(uid -> {
            try {
                run(event, uid);
            } catch (Exception ex) {
                log.error("SaveBlogger error. uid:" + uid, ex);
            }
        });
    }

    public void run(SaveBloggerEvent event, long uid) {
        BloggerResponse bloggerResponse = bloggerClient.get(uid);
        if (bloggerResponse == null || bloggerResponse.getUser() == null) {
            return;
        }
        Blogger blogger = bloggerMapper.mapper(bloggerResponse.getUser());
        if (event.needUpdate) {
            bloggerRepository.insertOrUpdate(blogger, event.getSource());
        } else {
            bloggerRepository.insertWhenNotExists(blogger, event.getSource());
        }
    }

    public static class SaveBloggerEvent extends Event {

        public SaveBloggerEvent(Event event, List<Long> uids, boolean needUpdate) {
            super(event, "SaveBlogger");
            this.uids = uids;
            this.needUpdate = needUpdate;
        }

        public SaveBloggerEvent(List<Long> uids, boolean needUpdate) {
            this(null, uids, needUpdate);
        }

        private List<Long> uids;

        private boolean needUpdate;
    }
}
